;(function($) {
    var js_input_osn = $("#js-input-osn"), // osn输入框
        js_query_osn = $("#js-query-osn"), // 查询合伙人信息按钮
        js_query_osn_dom = js_query_osn[0],
        js_data_list = $("#js-data-list"), // 数据列表
        js_data_list_td = js_data_list.find("td"), // 数据列表信息显示项
        js_error_tip = $("#js-error-tip"), // 显示错误信息
        url = "https://api.aizhifupay.cn/api/user/query_osn";

    // 清除字符串首尾两端的空白字符
    function trim(str) {
        var reg = /^\s+|\s+$/;
        return str.replace(reg, "");
    }

    //显示错误信息
    function showErrorMsg(msg) {
        js_data_list.addClass("hide");
        js_data_list_td.html("");
        js_error_tip.html(msg).removeClass("hide");
    }

    //隐藏错误信息
    function hideErrorMsg() {
        js_data_list.removeClass("hide");
        js_error_tip.addClass("hide").html("");
    }

    // 格式化手机号码
    function formatPhoneNum(phoneNum, interval, delimiter) {
        var reg = new RegExp("(?=\\B(\\d{" + interval + "})+$)", "g");
        return phoneNum.replace(reg, delimiter);
    }

    // 填充合伙人信息
    function fillData(data) {
        data = [data.nickName, formatPhoneNum(data.phone, 4, "-"), data.vipTypeName];
        var len = data.length,
        index = 0;
        while(index < len) {
            js_data_list_td.eq(index).html(data[index]);
            index++;
        }
        hideErrorMsg();
    }

    // 通过授权号获取合伙人信息
    function getPartnerInfoByOsn(osn) {
        $.ajax({
            url: url,
            type: "get",
            dataType: "json",
            data: {
                osn: osn
            },
            success: function(data) {
                if (data.status === 200) {
                    data = data.data;
                    fillData(data);
                } else {
                    showErrorMsg("请输入正确的官方授权号！");
                }
                js_query_osn_dom.canNotCommit = false;
            },
            error: function() {
                showErrorMsg("系统出现故障，查询出错！");
                js_query_osn_dom.canNotCommit = false;
            }
        });
    }

    // 点击查询授权合伙人信息
    js_query_osn.on({
        "click": function() {
            var osn = js_input_osn.val();
            osn = trim(osn);
            js_input_osn.val(osn);
            if (!osn.length) {
                showErrorMsg("请输入官方授权号！");
            } else if(!this.canNotCommit) {
                this.canNotCommit = true;
                getPartnerInfoByOsn(osn);
            }
        }
    });

    // 监听输入框上的事件
    js_input_osn.on({
        "keyup": function(e) {
            if (e.keyCode === 13) {
                js_query_osn.trigger("click");
            }
        }
    });
})(jQuery);